<?php

use Curl\Curl;
use extend\jiuwu;
use extend\kamun;
use extend\UserConf;
use lib\Hook\Hook;
use lib\Pay\Pay;


/**
 * 将秒数转换为剩余详细时间！
 */
function Sec2Time($time)
{
    if (is_numeric($time)) {
        $value = array(
            "years" => 0, "days" => 0, "hours" => 0,
            "minutes" => 0, "seconds" => 0,
        );
        if ($time >= 31556926) {
            $value["years"] = floor($time / 31556926);
            $time = ($time % 31556926);
        }
        if ($time >= 86400) {
            $value["days"] = floor($time / 86400);
            $time = ($time % 86400);
        }
        if ($time >= 3600) {
            $value["hours"] = floor($time / 3600);
            $time = ($time % 3600);
        }
        if ($time >= 60) {
            $value["minutes"] = floor($time / 60);
            $time = ($time % 60);
        }
        $value["seconds"] = floor($time);

        $t = ($value["years"] >= 1 ? $value["years"] . "年" : '') . ($value["days"] >= 1 ? $value["days"] . "天" : '') . ($value["hours"] >= 1 ? $value["hours"] . "小时" : '') . ($value["minutes"] >= 1 ? $value["minutes"] . "分" : '') . ($value["seconds"] >= 1 ? $value["seconds"] . "秒" : '');
        return (!empty($t) ? $t : '0秒');
    } else {
        return (bool)FALSE;
    }
}

/**
 * @param $startdate 开始时间
 * @param int $enddate 结束时间
 * 返回两者之间相差多少秒
 */
function TimeLag($startdate, $enddate = -1)
{
    global $date;
    $enddate = ($enddate == -1 ? $date : $enddate);
    $time = strtotime($enddate) - strtotime($startdate); //和结束时间的时间戳
    $text = '';
    $dater = floor(($time) / 86400);
    if ($dater > 0) {
        $time = $time - ($dater * 86400);
        $text .= $dater . '天';
    }

    $hour = floor(($time) / 3600);
    if ($hour > 0) {
        $time = $time - ($hour * 3600);
        $text .= $hour . '小时';
    }

    $minute = floor(($time) / 60);
    $time = $time - ($minute * 60);
    if ($minute > 0) {
        $text .= $minute . '分钟';
    }

    $second = floor(($time) % 60);
    if ($second > 0) {
        $text .= $second . '秒';
    }

    return $text;
}

/**
 * @param $vals 混淆函数
 * 生成唯一token参数！
 */
function TokenCreate($vals = '1')
{
    $key = mt_rand();
    $hash = hash_hmac("sha1", $vals . mt_rand() . time(), $key, true);
    return str_replace(['=', '_', '-'], '', strtr(base64_encode($hash), '+/', '-_'));
}

/**
 * @param string
 * @param string skey
 * @return string
 * 数据加密函数
 */
function xiaochu_en($string, $skey = 'xiaochuyun')
{
    $strArr = str_split(base64_encode($string));
    $strCount = count($strArr);
    foreach (str_split($skey) as $key => $value) {
        $key < $strCount && $strArr[$key] .= $value;
    }
    return str_replace(array('=', '+', '/'), array('O0O0O', 'o000o', 'oo00o'), join('', $strArr));
}

/**
 * @param $string
 * @param string $skey
 * @return false|string
 * 数据解密函数
 */
function xiaochu_de($string, $skey = 'xiaochuyun')
{
    $strArr = str_split(str_replace(array('O0O0O', 'o000o', 'oo00o'), array('=', '+', '/'), $string), 2);
    $strCount = count($strArr);
    foreach (str_split($skey) as $key => $value) {
        $key <= $strCount && isset($strArr[$key]) && $strArr[$key][1] === $value && $strArr[$key] = $strArr[$key][0];
    }
    return base64_decode(join('', $strArr));
}

function getBrowser()
{
    // 获取用户代理基本信息
    $flag = $_SERVER['HTTP_USER_AGENT'];
    // 定义一个空数组
    $para = array();
    // 检查操作系统
    if (preg_match('/Windows[\d\. \w]*/', $flag, $match)) $para['os'] = $match[0];

    if (preg_match('/Chrome\/[\d\.\w]*/', $flag, $match)) {
        // 检查Chrome
        $para['browser'] = $match[0];
    } elseif (preg_match('/Safari\/[\d\.\w]*/', $flag, $match)) {
        // 检查Safari
        $para['browser'] = $match[0];
    } elseif (preg_match('/MSIE [\d\.\w]*/', $flag, $match)) {
        // IE
        $para['browser'] = $match[0];
    } elseif (preg_match('/Opera\/[\d\.\w]*/', $flag, $match)) {
        // opera
        $para['browser'] = $match[0];
    } elseif (preg_match('/Firefox\/[\d\.\w]*/', $flag, $match)) {
        // Firefox
        $para['browser'] = $match[0];
    } elseif (preg_match('/OmniWeb\/(v*)([^\s|;]+)/i', $flag, $match)) {
        //OmniWeb
        $para['browser'] = $match[2];
    } elseif (preg_match('/Netscape([\d]*)\/([^\s]+)/i', $flag, $match)) {
        //Netscape
        $para['browser'] = $match[2];
    } elseif (preg_match('/Lynx\/([^\s]+)/i', $flag, $match)) {
        //Lynx
        $para['browser'] = $match[1];
    } elseif (preg_match('/360SE/i', $flag, $match)) {
        //360SE
        $para['browser'] = '360安全浏览器';
    } elseif (preg_match('/SE 2.x/i', $flag, $match)) {
        //搜狗
        $para['browser'] = '搜狗浏览器';
    } else {
        $para['browser'] = 'unkown';
    }
    // 数据返回
    return $para;
}

function saddslashes($string)
{
    if (is_array($string)) {
        foreach ($string as $key => $val) {
            $string[$key] = saddslashes($val);
        }
    } else {
        $string = addslashes($string);
    }
    return $string;
}

function dies($code, $msg)
{
    if ($_REQUEST['encrypt'] == 1) { #加密模式
        die(xiaochu_en(json_encode(['code' => $code, 'msg' => $msg])));
    } else {
        die(json_encode(['code' => $code, 'msg' => $msg]));
    }
}

function dier($arr)
{
    if ($_REQUEST['encrypt'] == 1) { #加密模式
        die(xiaochu_en(json_encode($arr)));
    } else {
        die(json_encode($arr));
    }
}

function fn_safe($str_string)
{
    //直接剔除
    /*$_arr_dangerChars = array(
        "|", ";", "$", "@", "+", "\t", "\r", "\n", ",", "(", ")", PHP_EOL //特殊字符
    );*/

    //正则剔除
    $_arr_dangerRegs = array(
        /* -------- 跨站 --------*/

        //html 标签
        "/<(script|frame|iframe|bgsound|link|object|applet|embed|blink|style|layer|ilayer|base|meta)\s+\S*>/i",

        //html 属性
        "/on(afterprint|beforeprint|beforeunload|error|haschange|load|message|offline|online|pagehide|pageshow|popstate|redo|resize|storage|undo|unload|blur|change|contextmenu|focus|formchange|forminput|input|invalid|reset|select|submit|keydown|keypress|keyup|click|dblclick|drag|dragend|dragenter|dragleave|dragover|dragstart|drop|mousedown|mousemove|mouseout|mouseover|mouseup|mousewheel|scroll|abort|canplay|canplaythrough|durationchange|emptied|ended|error|loadeddata|loadedmetadata|loadstart|pause|play|playing|progress|ratechange|readystatechange|seeked|seeking|stalled|suspend|timeupdate|volumechange|waiting)\s*=\s*(\"|')?\S*(\"|')?/i",

        //html 属性包含脚本
        "/\w+\s*=\s*(\"|')?(java|vb)script:\S*(\"|')?/i",

        //js 对象
        "/(document|location)\s*\.\s*\S*/i",

        //js 函数
        "/(eval|alert|prompt|msgbox)\s*\(.*\)/i",

        //css
        "/expression\s*:\s*\S*/i",

        /* -------- sql 注入 --------*/

        //显示 数据库 | 表 | 索引 | 字段
        "/show\s+(databases|tables|index|columns)/i",

        //创建 数据库 | 表 | 索引 | 视图 | 存储过程 | 存储过程
        "/create\s+(database|table|(unique\s+)?index|view|procedure|proc)/i",

        //更新 数据库 | 表
        "/alter\s+(database|table)/i",

        //丢弃 数据库 | 表 | 索引 | 视图 | 字段
        "/drop\s+(database|table|index|view|column)/i",

        //备份 数据库 | 日志
        "/backup\s+(database|log)/i",

        //初始化 表
        "/truncate\s+table/i",

        //替换 视图
        "/replace\s+view/i",

        //创建 | 更改 字段
        "/(add|change)\s+column/i",

        //选择 | 更新 | 删除 记录
        "/(select|update|delete)\s+\S*\s+from/i",

        //插入 记录 | 选择到文件
        "/insert\s+into/i",

        //sql 函数
        "/load_file\s*\(.*\)/i",

        //sql 其他
        "/(outfile|infile)\s+(\"|')?\S*(\"|')/i",
    );

    $_str_return = $str_string;
    //$_str_return = urlencode($_str_return);

    /*foreach ($_arr_dangerChars as $_key=>$_value) {
        $_str_return = str_ireplace($_value, "", $_str_return);
    }*/

    foreach ($_arr_dangerRegs as $_key => $_value) {
        $_str_return = preg_replace($_value, "", $_str_return);
    }

    //$_str_return = htmlentities($_str_return, ENT_QUOTES, "UTF-8", true); #再次实体化

    return $_str_return;
}

function daddslashes($string, $force = 0, $strip = false)
{
    !defined('MAGIC_QUOTES_GPC') && define('MAGIC_QUOTES_GPC', get_magic_quotes_gpc());
    if (!MAGIC_QUOTES_GPC || $force) {
        if (is_array($string)) {
            foreach ($string as $key => $val) {
                $val = fn_safe($val);
                $string[$key] = daddslashes($val, $force, $strip);
                $string[$key] = saddslashes($string[$key]);
                if (strpos($key, 'imageData') !== false) {
                    $string[$key]['tmp_name'] = fn_safe($val['tmp_name']);
                }
                if ($key == 'file' && $val['tmp_name'] <> '') { //图片上传本地地址白名单
                    $string[$key]['tmp_name'] = fn_safe($val['tmp_name']);
                }
            }
        } else {
            $string = htmlspecialchars($strip ? stripslashes($string) : $string);
            $string = saddslashes($string);
        }
    }
    return $string;
}

/**
 * @param $dir
 * @return array
 * 获取文件夹下的文件夹列表，1层
 */
function for_dir($dir)
{
    $files = array();
    if (@$handle = opendir($dir)) {
        while (($file = readdir($handle)) !== false) {
            if ($file != ".." && $file != ".") {
                $files[] = $file;
            }
        }
    }
    closedir($handle);
    return $files;
}

function get_curl($url, $post = 0, $referer = 0, $cookie = 0, $header = 0, $ua = 0, $nobaody = 0)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    $httpheader[] = "Accept: */*";
    $httpheader[] = "Accept-Encoding: gzip,deflate,sdch";
    $httpheader[] = "Accept-Language: zh-CN,zh;q=0.8";
    $httpheader[] = "Connection: close";
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    if ($post) {
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    }
    curl_setopt($ch, CURLOPT_HTTPHEADER, $httpheader);
    if ($header) {
        curl_setopt($ch, CURLOPT_HEADER, TRUE);
    }
    if ($cookie) {
        curl_setopt($ch, CURLOPT_COOKIE, $cookie);
    }
    if ($referer) {
        if ($referer == 1) {
            curl_setopt($ch, CURLOPT_REFERER, 'http://m.qzone.com/infocenter?g_f=');
        } else {
            curl_setopt($ch, CURLOPT_REFERER, $referer);
        }
    }
    if ($ua) {
        curl_setopt($ch, CURLOPT_USERAGENT, $ua);
    } else {
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36');
    }
    if ($nobaody) {
        curl_setopt($ch, CURLOPT_NOBODY, 1);
    }
    curl_setopt($ch, CURLOPT_ENCODING, "gzip");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $ret = curl_exec($ch);
    curl_close($ch);
    return $ret;
}


function show_msg($name = '温馨提示', $content = '未知的异常', $type = 4, $url = false, $true = true)
{
    global $conf;
    @header('Content-Type: text/html; charset=UTF-8');
    switch ($type) {
        case 1: #成功
            $panel = "btn-outline-success"; #绿色
            $bg = 'bg-success';
            break;
        case 2: #失败
            $panel = "btn-outline-warning"; #蓝色
            $bg = 'bg-warning';
            break;
        case 3: #普通
            $panel = "btn-outline-primary";
            $bg = 'bg-primary';
            break;
        case 4: #警告
            $panel = "btn-outline-danger"; #红色
            $bg = 'bg-danger';
            break;
        default:
            $panel = "btn-outline-primary";
            $bg = 'bg-primary';
            break;
    }
    $bgclass = background::image() == false ? 'background:#f9f9f9;' : background::image();
    echo '<!DOCTYPE html>
        <html lang="en" >
            <head>
                <meta charset="utf-8" />
                <title>' . $name . '</title>
                <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
                <meta content="Coderthemes" name="author" />
                <link rel="shortcut icon" href="' . is_https(false) . href() . '/assets/images/favicon.ico"/>
                <link href="' . is_https(false) . href() . '/assets/css/vendor/jquery-jvectormap-1.2.2.css"
                rel="stylesheet" type="text/css" />
                <link rel="stylesheet" type="text/css" href="' . is_https(false) . href() . '/assets/layui/css/layui.css"/>
                <link href="' . is_https(false) . href() . '/assets/css/icons.min.css" rel="stylesheet"
                type="text/css" />
                <link href="' . is_https(false) . href() . '/assets/css/app.min.css" rel="stylesheet"
                type="text/css" />
            </head>
            <body  style="' . $bgclass . '">
            <style>.imagtes img{
        max-width: 100%;
        display: block;
        margin:auto;
    }</style>
                <div class="wrapper" style="padding: 1em">
                    <div class="row">
                        <div class="col-xl-6 m-auto text-left">
                            <div class="card">
                                <h5 class="card-header ' . $bg . ' text-white">
                                    ' . $name . '
                                </h5>
                                <div class="card-body imagtes">
                                    <p class="card-text font-16">
                                       ' . $content . '
                                    </p>';
    if ($true == true) {
        if ($url <> '') {
            echo '<a href="' . $url . '" class="btn ' . $panel . ' btn-sm btn-block">进入下一页</a>';
        } else {
            echo '<a href="javascript:history.back(-1)" class="btn ' . $panel . ' btn-sm btn-block">返回上一页</a>';
        }
    }
    echo '
                                </div>
                                <!-- end card-body-->
                            </div>
                            <!-- end card-->
                        </div>
                        <!-- end col-->
                    </div>
                </div>
            </body>
        </html>';
    include "bottom.php";
    exit();
}

function IP_user()
{
    $ip = $_SERVER['REMOTE_ADDR'];
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && preg_match_all('#\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}#s', $_SERVER['HTTP_X_FORWARDED_FOR'], $matches)) {
        foreach ($matches[0] as $xip) {
            if (!preg_match('#^(10|172\.16|192\.168)\.#', $xip)) {
                $ip = $xip;
                break;
            }
        }
    } elseif (isset($_SERVER['HTTP_CLIENT_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (isset($_SERVER['HTTP_CF_CONNECTING_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CF_CONNECTING_IP'])) {
        $ip = $_SERVER['HTTP_CF_CONNECTING_IP'];
    } elseif (isset($_SERVER['HTTP_X_REAL_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_X_REAL_IP'])) {
        $ip = $_SERVER['HTTP_X_REAL_IP'];
    }
    return $ip;
}

function array_key_yz($arr, $str = '')
{
    foreach ($arr as $k => $v) { #取出
        if (strstr($str, $k)) continue;
        if (!isset($v)) {
            exit('{"code":-2,"msg":"请填写完整：' . $k . '"}');
        } else continue;
    }
}

function userlog($name, $content, $uid, $count = 0)
{
    global $date;
    $DBS = \Medoo\DB\SQL::DB();
    if (!$uid) {
        $USERDATA = \login_data::user_data();
        $uid = $USERDATA['id'];
    }
    $IP = IP_user();
    $Res = $DBS->insert('journal', [
        'ip' => $IP,
        'uid' => $uid,
        'count' => $count,
        'name' => $name,
        'content' => $content,
        'date' => $date
    ]);
    if ($Res) {
        return true;
    } else {
        return false;
    }
}

function href()
{
    return $_SERVER['HTTP_HOST'];
}

class config
{
    /**
     * 取出公告内容.
     * 分站不需要改动，仅优化读取即可
     */
    public static function Notice()
    {
        mkdirs(ROOT . '/includes/extend/log/Notice/');
        return [
            'notice_top' => self::NoticeRead('notice_top'),
            'notice_check' => self::NoticeRead('notice_check'),
            'notice_bottom' => self::NoticeRead('notice_bottom'),
            'notice_user' => self::NoticeRead('notice_user'),
            'PopupNotice' => self::NoticeRead('PopupNotice'),
            'statistics' => self::NoticeRead('statistics'),
            'ServiceTips' => self::NoticeRead('ServiceTips'),
        ];
    }

    /**
     * @param $Nc
     * @return false|string
     */
    public static function NoticeRead($Nc)
    {
        if (!file_exists(ROOT . '/includes/extend/log/Notice/' . $Nc . '.nc')) return '';
        return file_get_contents(ROOT . '/includes/extend/log/Notice/' . $Nc . '.nc');
    }

    public static function data_cache()
    {
        $DB = \Medoo\DB\SQL::DB();
        $br = $DB->get('cache', '*', ['K' => 'config']);
        if (!$br || !empty($br['V'])) {
            self::serialize_array();
        }
        $data = [];
        foreach (self::common_unserialize($br['V']) as $Key => $v) {
            $data += $v;
        }
        $Arr = [];
        if (self::func_is_base64($data['currency']) === false) {
            $Type = 1;
        } else {
            $Type = 2;
        }
        foreach ($data as $key => $value) {
            $Arr += [$key => ($Type === 1 ? $value : base64_decode($value))];
        }
        $Arr = array_merge($Arr, self::Notice());
        $Arr = extend\UserConf::Conf($Arr);
        return $Arr;
    }

    public static function func_is_base64($str)
    {
        return $str == base64_encode(base64_decode($str)) ? true : false;
    }

    public static function serialize_array()
    {
        $DB = \Medoo\DB\SQL::DB();
        $br = $DB->get('cache', '*', ['K' => 'config']);
        if (!$br) {
            @$DB->insert('cache', [
                'K' => 'config'
            ]);
        }
        if ($br['V'] == '') {
            $Data = $DB->select('config', '*');
            $Array = [];
            foreach ($Data as $v) {
                $Array[] = [
                    $v['K'] => base64_encode($v['V'])
                ];
            }
            $ar = serialize($Array);
            $DB->update('cache', [
                'V' => $ar
            ], [
                'K' => 'config'
            ]);
        }
    }

    public static function common_unserialize($serial_str)
    {
        $serial_str = preg_replace_callback('/s:(\d+):"([\s\S]*?)";/', function ($matches) {
            return 's:' . strlen($matches[2]) . ':"' . $matches[2] . '";';
        }, $serial_str);
        return unserialize($serial_str);
    }

    public function unset_cache()
    {
        global $DB;
        $DB = \Medoo\DB\SQL::DB();
        $Res = $DB->update('cache', [
            'V' => ''
        ], [
            'K' => 'config'
        ]);
        if ($Res) {
            return true;
        } else {
            return false;
        }
    }
}

class template
{
    public static function get($mod)
    {
        global $_QET, $conf;
        if (self::isMobile() == true) {
            if ($conf['template_m'] == -1) {
                show_msg('温馨提示', '<center><h4>请使用电脑打开本站<br><br>当前访问地址：<a target="_blank" href="' . is_https(false) . href() . $_SERVER['REQUEST_URI'] . '">' . is_https(false) . href() . $_SERVER['REQUEST_URI'] . '</a></h4></center>', false, false, false);
            }
            if ($conf['template'] == -2 && strstr($_SERVER['REQUEST_URI'], '/?mod=Frame')) header("Location:/");
            $conf['template'] = $conf['template_m'];
        } else {
            if ($conf['template'] == -1) {
                $Image = QR_Code(1, is_https(false) . href() . $_SERVER['REQUEST_URI'], 10, 1, SYSTEM_ROOT . 'extend/log/ShopImage/' . md5(is_https(false) . href() . $_SERVER['REQUEST_URI']) . '.png', '/includes/extend/log/ShopImage/' . md5(is_https(false) . href() . $_SERVER['REQUEST_URI']) . '.png');
                show_msg('温馨提示', '<center><h4>请使用手机打开本站<br><br>当前访问地址：<a target="_blank" href="' . is_https(false) . href() . $_SERVER['REQUEST_URI'] . '">' . is_https(false) . href() . $_SERVER['REQUEST_URI'] . '</a></h4><hr><img style="box-shadow: 3px 3px 16px #ccc;border-radius: 0.5rem" src="' . $Image . '" width="350px" ><h4><br>请拿出手机扫一扫进入</h4></center>', false, false, false);
            } else if ($conf['template'] == -2 && strstr($_SERVER['REQUEST_URI'], '/?mod=Frame')) {
                $conf['template'] = $conf['template_m'];
            } else if ($conf['template'] == -2 && !strstr($_SERVER['REQUEST_URI'], '/?mod=Frame')) {
                $conf['template'] = $conf['template_m'];
                echo '<script> if(window.top == window.self){window.location= "' . "/?mod=Frame&Url=" . xiaochu_en(is_https(false) . href() . $_SERVER['REQUEST_URI']) . '" };</script>' . "\n";
            }
        }

        if (!empty($mod)) {
            /**
             * 载入首页扩展
             */
            \lib\Hook\Hook::execute('VisitMod', $_QET);
            $file = ROOT . 'template/' . $conf['template'] . '/' . $mod . '.php';
            if (!file_exists($file)) {
                $file = ROOT . 'template/default/' . $mod . '.php';
                if (!file_exists($file)) show_msg('警告', $mod . '.php扩展文件不存在,点击下方按钮返回!', 3, '/');
            }
        } else {
            /**
             * 载入首页模板
             */
            $file = ROOT . 'template/' . $conf['template'] . '/index.php';
            if (!file_exists($file)) {
                $file = ROOT . 'template/default/index.php';
            }
            \lib\Hook\Hook::execute('VisitHome');
        }
        mkdirs(ROOT . '/includes/extend/log/Home/');
        $Flie = ROOT . '/includes/extend/log/Home/Cache_' . md5($file . $_COOKIE['THEKEY'] . $_SERVER['QUERY_STRING'] . href() . (self::isMobile() == true ? '1' : '2')) . '.html';
        if (is_file($Flie) && (time() - filemtime($Flie)) < $conf['Homecaching']) {
            require_once($Flie);
        } else {
            global $_QET, $DB, $times, $cdnpublic, $accredit, $cdnserver;
            ob_start();
            echo '<!--' . "\n" . '页面缓存周期：' . $conf['Homecaching'] . '秒' . "\n" . '页面缓存时间：' . date('Y-m-d H:i:s') . "\n"
                . '缓存文件名称：' . md5($file . userip()) . '.html' . "\n" . '若您发现此站点存在违法商品,可联系客服：2221186349举报,举报时带上违法商品截图！' . "\n" . '-->' . "\n\n";
            include_once $file;
            self::clear($conf['Homecaching'] * 1.1);
            $flie_view = str_replace(["\r\n", ' ', '  ', '   ', '    ', '     ', '      ', '       ', '   '], ' ', ob_get_flush());
            file_put_contents($Flie, $flie_view);
        }
    }

    /**
     * 判断是否在QQ或微信内打开
     */
    public static function WeixQqV()
    {
        $bro_msg = $_SERVER['HTTP_USER_AGENT'];
        if (strpos($bro_msg, 'iPhone') || strpos($bro_msg, 'iPad')) {
            if (strpos($_SERVER['HTTP_USER_AGENT'], ' QQ') !== false)
                return 'iosqq';
        }
        if (strpos($bro_msg, 'Android')) {
            if (strpos($bro_msg, 'MQQBrowser') !== false) {
                if (strpos($bro_msg, ' QQ') !== false)
                    return 'qq';
            }
        }
        $bro_msg = $_SERVER['HTTP_USER_AGENT'];
        if (strpos($bro_msg, 'MicroMessenger') !== false) {
            return 'wx';
        }
        return false;
    }

    /**
     * @param int $nus
     * 缓存文件清理
     */
    public static function clear($nus = 60)
    {
        $Flies = ROOT . '/includes/extend/log/Home/';
        $arr = scandir($Flies);
        foreach ($arr as $re) {
            if ($re == '.' || $re == '..') continue;
            $fea = $Flies . $re;
            if (is_file($fea) && (time() - filemtime($fea)) < $nus) {
                @unlink($fea);
            }
        }
    }

    /**
     * @return bool
     * 判断是否是移动端打开
     */
    public static function isMobile()
    {
        if (isset($_SERVER['HTTP_X_WAP_PROFILE'])) {
            return true;
        }
        if (isset($_SERVER['HTTP_VIA'])) {
            return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
        }
        if (isset($_SERVER['HTTP_USER_AGENT'])) {
            $clientkeywords = array('nokia', 'sony', 'ericsson', 'mot', 'samsung', 'htc', 'sgh', 'lg', 'sharp', 'sie-', 'philips', 'panasonic', 'alcatel', 'lenovo', 'iphone', 'ipod', 'blackberry', 'meizu', 'android', 'netfront', 'symbian', 'ucweb', 'windowsce', 'palm', 'operamini', 'operamobi', 'openwave', 'nexusone', 'cldc', 'midp', 'wap', 'mobile', 'MicroMessenger');
            if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
                return true;
            }
        }
        if (isset($_SERVER['HTTP_ACCEPT'])) {
            if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
                return true;
            }
        }
        return false;
    }
}

class notice
{
    public static function user_notice($USERDATA = false)
    {
        global $DB;
        if ($USERDATA == false) {
            $USERDATA['id'] = '-1';
        }
        $rs = $DB->query("SELECT * FROM `sky_notice` ORDER BY `date` DESC");
        $arra = array();
        $ppt = 0;
        while ($res = $DB->fetch($rs)) {
            $ace = explode('|', $res['browse']);
            if (in_array($USERDATA['id'], $ace)) {
                $browse = 1; #已读
            } else {
                $ppt = 1;
                $browse = 2; #未读
            }
            $arra[] = array(
                'title' => $res['title'],
                'id' => $res['id'],
                'date' => $res['date'],
                'browse' => $browse
            );
            unset($ace, $browse); #清理
        }
        return array('code' => $ppt, 'msg' => '消息提醒', 'data' => $arra);
    }

    public static function user_particulars($id, $USERDATA = [])
    {
        $DB = \Medoo\DB\SQL::DB();
        $a = $DB->get('notice', '*', [
            'id' => $id
        ]);
        if ($a) {
            $b = explode('|', $a['browse']);
            $count = count($b);
            if (!in_array($USERDATA['id'], $b)) { #此用户未读
                if ($a['browse'] == '') { #第一位阅读的人
                    $browse = $USERDATA['id'];
                } else {
                    $browse = $a['browse'] . '|' . $USERDATA['id'];
                }
                @$DB->update('notice', [
                    'browse' => $browse,
                ], [
                    'id' => $id
                ]);
            }
            $a['content'] = htmlspecialchars_decode(base64_decode($a['content']));
            show_msg($a['title'], $a['content'] . '<br><br><hr>你好:' . $USERDATA['name'] . '<br><span class="font-14 text-secondary">发布时间：' . $a['date'] . '</span><br>已读用户：' . $count . '人 <img src="' . $USERDATA['image'] . '" width="16" />', 1);
        } else {
            show_msg('文章不存在', '文章不存在,请返回列表重新刷新界面查看', 3);
        }
    }
}

class reward
{
    public static function prevent($url, $type = 2)
    {
        global $conf;
        $url2 = $url;
        $url = urlencode($url);
        if ($type == 2 && isset($_COOKIE[$conf['prevent_return'] . '_' . md5($url)])) {
            return base64_decode($_COOKIE[$conf['prevent_return'] . '_' . md5($url)]);
        }
        if ($conf['prevent_switch'] == 1) {
            if ($conf['prevent_url'] == '') return $url2;
            $UrlField = html_entity_decode($conf['prevent_field']);
            $UrlField = str_replace('[url]', $url, $UrlField);
            $UrlField = str_replace('[ip]', userip(), $UrlField);
            $UrlField = str_replace('[time]', time(), $UrlField);
            $UrlField = str_replace('[sitename]', $conf['sitename'], $UrlField);
            $UrlField = str_replace('[http]', is_https(false), $UrlField);
            $data = get_curl($conf['prevent_url'] . $UrlField);
            $data = json_decode($data, TRUE);
            if (isset($data[$conf['prevent_return']])) {
                setcookie($conf['prevent_return'] . '_' . md5($url), base64_encode($data[$conf['prevent_return']]), time() + 3600 * 12, '/');
                return $data[$conf['prevent_return']];
            } else  return $url2;
        } else return $url2;
    }

    public function user_payet($money, $type, $USERDATA)
    {
        $Res = Pay::PrepaidPhoneOrders([
            'type' => $type,
            'uid' => $USERDATA['id'],
            'gid' => -1,
            'input' => -1,
            'num' => 1
        ], [
            'name' => '用户:[' . $USERDATA['id'] . '] 在线充值',
            'price' => $money
        ]);
        dier($Res);
    }

    public function user_pays($USERDATA)
    {
        global $times, $timea;
        $DB = \Medoo\DB\SQL::DB();

        $Count1 = $DB->sum('journal', 'count', [
            'uid' => $USERDATA['id'],
            'name' => ['后台扣款', '等级提升', '域名绑定', '余额购买', '在线购买']
        ]);

        $Count2 = $DB->sum('journal', 'count', [
            'uid' => $USERDATA['id'],
            'name' => ['每日签到', '邀请奖励', '货币提成', '积分充值'],
            'date[>=]' => $times
        ]);

        $Count3 = $DB->sum('journal', 'count', [
            'uid' => $USERDATA['id'],
            'name' => ['每日签到', '邀请奖励', '货币提成', '积分充值'],
            'date[<]' => $times,
            'date[>=]' => $timea
        ]);

        return [
            'Count1' => round($Count1, 2), //累计消费
            'Count2' => round($Count2, 0), //今日获得积分
            'Count3' => round($Count3, 0), //昨日获得积分
        ];
    }

    public static function user_landing()
    {
        $DB = \Medoo\DB\SQL::DB();
        if (!empty($_COOKIE['THEKEY'])) {
            $idu = daddslashes($_COOKIE['THEKEY']);
            if (strlen($_COOKIE['THEKEY']) == 32) {
                $user_row = $DB->get('user', '*', ['user_idu' => $idu, 'state' => 1, 'LIMIT' => 1]);
            } else {
                $user_row = $DB->get('user', '*', ['wx_idu' => $idu, 'state' => 1, 'LIMIT' => 1]);
            }
            if (!$user_row) {
                return 0;
            }
            return 1;
        } else {
            return 0;
        }
    }

    public function ranking_list($sum = 20)
    {
        $sum = (int)$sum;
        global $DB, $times;
        $sql = "select a.uid,(select b.name from sky_user as b where a.uid=b.id) as name,(select b.image from sky_user as b where a.uid=b.id) as image,count(id) as count,sum(count) as money from sky_journal as a where `date`>'$times' and `name` = '邀请奖励' group by uid order  by count desc  limit $sum "; #查询邀请排行榜
        $rs = $DB->query($sql);
        $arr_1 = [];
        while ($res = $DB->fetch($rs)) {
            $arr_1[] = $res;
        }

        $sql = "select a.uid,(select b.name from sky_user as b where a.uid=b.id) as name,(select b.image from sky_user as b where a.uid=b.id) as image,count(id) as count,sum(count) as money from sky_journal as a where   `name` = '邀请奖励' group by uid order  by count desc  limit $sum "; #查询总请排行榜
        $rs = $DB->query($sql);
        $arr_2 = [];
        while ($res = $DB->fetch($rs)) {
            $arr_2[] = $res;
        }

        $sql = "SELECT * FROM `sky_user` ORDER BY `currency` DESC LIMIT $sum "; #查询剩余额度排行
        $rs = $DB->query($sql);
        $arr_3 = [];
        while ($res = $DB->fetch($rs)) {
            if ($res['currency'] > 0) {
                $arr_3[] = [
                    'id' => $res['id'],
                    'name' => $res['name'],
                    'image' => $res['image'],
                    'currency' => $res['currency']
                ];
            }
        }

        $sql = "SELECT * FROM `sky_user` ORDER BY `money` DESC LIMIT $sum "; #查询金额排行榜
        $rs = $DB->query($sql);
        $arr_4 = [];
        while ($res = $DB->fetch($rs)) {
            $arr_4[] = $res;
        }

        $sql = "select a.uid ,(select b.name from sky_user as b where a.uid=b.id) as name,(select b.image from sky_user as b where a.uid=b.id) as image , sum(a.count) as money from `sky_journal` as a where `name` = '在线购买' or  `name` = '余额购买' group by uid order  by money desc  limit $sum "; #查询消费排行榜
        $rs = $DB->query($sql);
        $arr_5 = [];
        while ($res = $DB->fetch($rs)) {
            $arr_5[] = $res;
        }
        return [
            'data_1' => $arr_1, #今日邀请排行
            'data_2' => $arr_2, #昨日邀请排行
            'data_3' => $arr_3, #用户余额排行
            'data_4' => $arr_4, #余额排行榜
            'data_5' => $arr_5, #消费排行榜
        ];
    } #信息统计

    public function statistics($ID)
    {
        global $DB, $times, $timea;
        $count_1 = $DB->count("SELECT count(*) FROM `sky_order`  WHERE `uid` = '$ID' ");
        $count_2 = $DB->count("SELECT sum(count) FROM `sky_journal` WHERE (`name` = '在线购买' or `name` = '余额购买') AND`uid` = '$ID' ");
        $count_3 = $DB->count("SELECT count(*) FROM `sky_journal` WHERE `name` = '邀请奖励' AND `uid` = '$ID' ");
        $count_4 = $DB->count("SELECT count(*) FROM `sky_journal` WHERE `name` = '邀请奖励' AND `uid` = '$ID' ");
        $array = [
            'count_1' => $count_1, //订单总数
            'count_2' => $count_2, //累计消费
            'count_3' => $count_3, //累计邀请
            'count_4' => $count_4, //累计奖励
        ];
        return $array;
    } #reward

    /**
     * @param $USERDATA
     * @param $id
     * 奖励领取！
     */
    public function issue_reward($USERDATA, $id)
    {
        global $DB, $date, $conf;
        $DB = \Medoo\DB\SQL::DB();
        $rs = $DB->get('invite', '*', [
            'uid' => $USERDATA['id'],
            'id' => $id
        ]);
        if ($rs) { #存在
            $rs2 = $DB->get('user', '*', [
                'id' => $rs['invitee']
            ]);
            if ($rs['award'] == 0) {
                show_msg('领取失败提醒', '受邀用户：' . $rs2['name'] . ' <img src="' . $rs2['image'] . '" width="20" style="border-radius: 3em"><br>邀请时间：' . $rs['creation_time'] . '<br>领取时间：' . $rs['draw_time'] . '<br>奖励状态：您已经领取过一次奖励了,无法再次领取哦!,可以去多邀请人，奖励就会与越来越多的！', 4, './activity.php');
            } else { #发放

                if ($conf['InviteValve'] != 0) {
                    /**
                     * 验证消费是否达标
                     */
                    $Sum = $DB->sum('order', 'money', [
                        'uid' => $rs['invitee'],
                        'payment[!]' => ['免费领取', '积分兑换']
                    ]);
                    if ($Sum < (float)$conf['InviteValve']) {
                        show_msg('领取失败提醒', '您的邀请对象：' . $rs2['name'] . '未满足，累计消费' . $conf['InviteValve'] . '元的条件，您无法领取邀请奖励！', 4, './activity.php');
                    }
                }

                userlog('邀请奖励', '您在' . $date . '成功领取了' . $rs['award'] . '邀请奖励点！再接再厉哦！', $USERDATA['id'], $rs['award']);
                $alett = $DB->get('user', '*', [
                    'id' => $USERDATA['id']
                ]);

                $ia = $alett['currency'] + $rs['award'];
                $ac = $DB->update('user', [
                    'currency' => $ia,
                ], [
                    'id' => $USERDATA['id']
                ]);

                $ad = $DB->update('invite', [
                    'award' => 0,
                    'draw_time' => $date,
                ], [
                    'uid' => $USERDATA['id'],
                    'id' => $id
                ]);

                if ($ac && $ad) {
                    show_msg('奖励发放成功提醒', '受邀用户：' . $rs2['name'] . ' <img src="' . $rs2['image'] . '" width="20" style="border-radius: 3em"><br>邀请时间：' . $rs['creation_time'] . '<br>领取时间：' . $date . '<br>奖励状态：恭喜您，您成功领取了' . $rs['award'] . '个奖励点,快去兑换商品吧,再接再厉哦！', 1, './activity.php');
                } else {
                    show_msg('领取失败提醒', '抱歉，领取失败了，请联系管理员处理！', 4, './activity.php');
                }
            }
        } else { #不存在
            show_msg('奖励订单不存在', '奖励订单不存在,错误提示：<br>' . $DB->error(), 4, './activity.php');
        }
    }

    /**
     * @param $USERDATA
     * @return array
     * 查询邀请列表
     */
    public function Invite_statistics($USERDATA)
    {
        $DB = \Medoo\DB\SQL::DB();
        $Res = $DB->select('invite', '*', [
            'uid' => $USERDATA['id'],
            'ORDER' => [
                'id' => 'DESC'
            ],
            'LIMIT' => 28
        ]);

        $Data = [];
        foreach ($Res as $v) {
            $a = $DB->get('user', ['image', 'name'], [
                'id' => $v['invitee']
            ]);
            $v['image'] = $a['image'];
            $v['name'] = $a['name'];
            $Data[] = $v;
        }
        return $Data;
    }

    public function Invited_status($s, $i)
    {
        $DB = \Medoo\DB\SQL::DB();
        $i = intval($i);
        $yoid = $DB->get('user', '*', ['id' => $i, 'LIMIT' => 1]);
        if ($yoid && md5($yoid['user_idu']) == $s) {
            setcookie("INVITED_STATUS", $yoid['id'], time() + 3600 * 12 * 15, '/');
            $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
            $URLS = $http_type . $_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'];
            header("Location:$URLS");
            return false;
        }
    }

    public function welfare($USERDATA)
    {
        global $DB, $conf;
        $thtime = date("Y-m-d") . ' 00:00:00';
        $a = $DB->get_row("SELECT * FROM `sky_journal` WHERE `name` = '每日签到' AND `uid` = '{$USERDATA['id']}' AND `date` >= '$thtime' ");
        if ($a) {
            show_msg('签到失败提醒', '您已经签到过了,请明天再来哦~', '4');
        } else {
            $b = $DB->query("UPDATE `sky_user` SET `currency`= `currency`+{$conf['Signin']} WHERE  `id` = '{$USERDATA['id']}' ");
            if ($b) {
                userlog('每日签到', '恭喜您签到成功,赠送您' . $conf['Signin'] . '点' . $conf['currency'], $USERDATA['id'], $conf['Signin']);
                Hook::execute('UserSignIn', [
                    'id' => $USERDATA['id'],
                    'num' => $conf['Signin']
                ]);
                show_msg('签到成功提醒', '恭喜您签到成功,赠送您' . $conf['Signin'] . '点' . $conf['currency'] . ',可用于领取今日免费商品福利！记得明天再来签到哦~', '1');
            } else {
                show_msg('签到失败提醒', '因程序原因，签到失败了,错误码：<br>' . $DB->error(), '4');
            }
        }
    }

    public function welfare_judge($USERDATA)
    {
        global $DB;
        $thtime = date("Y-m-d") . ' 00:00:00';
        $a = $DB->get_row("SELECT * FROM `sky_journal` WHERE `name` = '每日签到' AND `uid` = '{$USERDATA['id']}' AND `date` >= '$thtime' ");
        if ($a) {
            return 1;
        } else {
            return 2;
        }
    }

    /**
     * @param $USERDATA 用户信息
     * @return string
     */
    public function shareLink($USERDATA)
    {
        $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
        $shareLink = $http_type . $_SERVER['HTTP_HOST'] . '/?s=' . md5($USERDATA['user_idu']) . '&id=' . $USERDATA['id'];
        return $shareLink;
    }
}

/**
 * Class login_data
 * 用户登陆模块
 */
class login_data
{
    /**
     * @return string
     */
    public function image_user()
    {
        $date_img = get_curl('https://cn.bing.com/HPImageArchive.aspx?format=js&idx=' . rand(0, 7) . '&n=8');
        $date_img = json_decode($date_img, true);
        $conetr = count($date_img['images']);
        $background_image = 'https://cn.bing.com' . $date_img['images'][rand(0, $conetr - 1)]['url'];
        return $background_image;
    } #取出图片

    /**
     * @param $uid
     * 根据用户名ID取出等级！
     */
    public static function user_grade($uid)
    {
        global $conf;
        if ($conf['ShutDownUserSystem'] == -1) return -1;
        $DB = \Medoo\DB\SQL::DB();
        if ($uid == -1) {
            return -1; //游客
        } else {
            $G = $DB->get('user', [
                'grade'
            ], [
                'id' => $uid
            ]);
            return $G['grade'];
        }
    }

    public static function user_data()
    {
        global $conf;
        if ($conf['ShutDownUserSystem'] == -1) return false;
        $DB = \Medoo\DB\SQL::DB();
        if (reward::user_landing() == 1) {
            $idu = daddslashes($_COOKIE['THEKEY']);
            if (strlen($_COOKIE['THEKEY']) == 32) {
                $user_row = $DB->get('user', '*', ['user_idu' => $idu, 'LIMIT' => 1]);
            } else {
                $user_row = $DB->get('user', '*', ['wx_idu' => $idu, 'LIMIT' => 1]);
            }
            return $user_row;
        } else {
            return false;
        }
    }

    /**
     * @return array|bool|mixed|string[]|null
     * 分站用户登陆验证
     */
    public static function login_verify()
    {
        global $conf;
        if ($conf['ShutDownUserSystem'] == -1) return false;
        $DB = \Medoo\DB\SQL::DB();
        if (empty($_COOKIE['THEKEY'])) {
            header("Location:" . is_https(false) . href() . "/user/login.php");
            return false;
        } else {
            if (strlen($_COOKIE['THEKEY']) == 32) {
                $user_row = $DB->get('user', '*', ['user_idu' => $_COOKIE['THEKEY'], 'state' => 1, 'LIMIT' => 1]);
            } else {
                $user_row = $DB->get('user', '*', ['wx_idu' => $_COOKIE['THEKEY'], 'state' => 1, 'LIMIT' => 1]);
            }
            if (!$user_row) {
                setcookie("THEKEY", null, time() - 3600 * 12 * 15, '/');
                header("Location:" . is_https(false) . href() . "/user/login.php");
                return false;
            } else {
                return $user_row;
            }
        }
    }

    public static function login_close()
    {
        global $USERDATA;
        setcookie("THEKEY", null, time() - 3600 * 12 * 15, '/');
        Hook::execute('UserLogout', [
            'name' => $USERDATA['name'],
            'id' => $USERDATA['id']
        ]);
        show_msg('操作成功', '成功退出登陆!', '1', './login.php');
    }

    public static function login($suffix)
    {
        global $accredit;
        $url = href() . $suffix;
        $url = xiaochu_de('axHiRa0occDhouvyLu2nNkbi43OXRpYW4uY29tL3FxYXBpL2FwaS5waHAoo00oYWN0PXNwb25zb3ImdXJsPQO0O0OO0O0O') . $url;
        setcookie("PHPTOKEN", md5($accredit['token'] . 'login'), time() + 3600, '/');
        header('Location: ' . $url);
    }

    /**
     * @param $_QET 回调参数
     * 重新绑定互联
     */
    public function user_reception($_QET)
    {
        global $date, $USERDATA;
        $DB = \Medoo\DB\SQL::DB();
        /**
         * 验证数据
         */
        if (empty($_QET['data'])) {
            show_msg('数据异常', '检测到数据异常,请重新发起验证', '3', './index.php');
        } else {
            $data = base64_decode($_QET['data']);
            $data = json_decode($data, true);
            if ($data['code'] <> 1) { #有错误
                show_msg('温馨提示', $data['msg'] . '=>' . $data['error'], '3', './index.php');
            } else {
                if ($USERDATA['user_idu'] == '') show_msg('温馨提示', '请先完成登陆！', '3', './index.php');
                /**
                 * 更新用户数据
                 */

                $red = $DB->get('user', '*', [
                    'user_idu' => $date['user_idu'],
                    'id[!]' => $USERDATA['id']
                ]);

                if ($red) show_msg('警告', '您当前新绑定的QQ账号 [ <img src="' . $data['data']['figureurl_2'] . '" width="20" /> ' . $data['data']['nickname'] . ' ] 已经被用户：' . $red['id'] . ' 绑定过了', '3', './index.php');
                if ($USERDATA['user_idu'] == $data['user_idu']) show_msg('温馨提示', '新绑定的QQ和旧的一致，无需修改！', '3', './index.php');
                $Res = $DB->update('user', [
                    'user_idu' => $date['user_idu'],
                    'image' => $data['data']['figureurl_2'],
                    'name' => $data['data']['nickname'],
                ], [
                    'id' => $USERDATA['id'],
                    'user_idu' => $USERDATA['user_idu']
                ]);
                if ($Res) {
                    userlog('QQ换绑', '用户于' . $date . '将QQ登陆账号修改为：' . $data['user_idu'], $USERDATA['id']);
                    $c = base64_encode(json_encode($data['data']));
                    setcookie("THEKEY", $data['user_idu'], time() + 3600 * 12 * 15, '/');
                    show_msg('温馨提示', '您的账户绑定QQ已经修改为 [ <img src="' . $data['data']['figureurl_2'] . '" width="20" /> ' . $data['data']['nickname'] . ' ] <br>以后用新绑定的QQ账号登陆即可！', '1', './index.php');
                } else show_msg('警告', '绑定失败,请重新尝试！<br>' . $DB->error(), '3', './index.php');
            }
        }
    }

    /**
     * @param $_QET
     * @return bool
     */
    public function login_reception($_QET)
    {
        /**
         * COOKIE 登陆
         */
        global $date, $conf, $accredit;
        $DB = \Medoo\DB\SQL::DB();
        $IP = IP_user();
        if (empty($_COOKIE['PHPTOKEN']) || $_COOKIE['PHPTOKEN'] != md5($accredit['token'] . 'login')) show_msg('警告', '登陆已超时，请重新登陆', '2', './login.php');
        if (empty($_QET['data'])) {
            show_msg('数据异常', '检测到数据异常,请重新登陆', '4', './login.php');
        } else {
            $data = base64_decode($_QET['data']);
            $data = json_decode($data, true);
            $data['data']['figureurl_2'] = str_replace('http://', 'https://', $data['data']['figureurl_2']);
            if ($data['code'] <> 1) {
                show_msg('温馨提示', $data['msg'] . '=>' . $data['error'], '4', './login.php');
            } else {
                $a = $DB->get('user', '*', [
                    'user_idu' => $data['user_idu'],
                ]);
                if ($a) {
                    userlog('用户登陆', '用户登陆了后台', $a['id']);
                    $b = $DB->update('user', [
                        'ip' => $IP,
                        'image' => $data['data']['figureurl_2'],
                        'name' => $data['data']['nickname']
                    ], [
                        'user_idu' => $data['user_idu']
                    ]);
                } else {
                    $Uty = UserConf::judge();
                    if ($Uty == false) {
                        $Uty = 0;
                    } else $Uty = $Uty['id'];
                    if (empty($_COOKIE['INVITED_STATUS'])) {
                        $b = $DB->insert('user', [
                            'grade' => $conf['userdefaultgrade'],
                            'user_idu' => $data['user_idu'],
                            'superior' => $Uty,
                            'currency' => 0,
                            'ip' => $IP,
                            'image' => $data['data']['figureurl_2'],
                            'name' => $data['data']['nickname'],
                            'state' => 1,
                            'recent_time' => $date,
                            'found_date' => $date
                        ]);
                    } else {
                        $c = $DB->get('user', '*', ['id' => $_COOKIE['INVITED_STATUS']]);
                        if ($c) {
                            $GETTE = 1;
                            $b = $DB->insert('user', [
                                'grade' => $conf['userdefaultgrade'],
                                'user_idu' => $data['user_idu'],
                                'superior' => $_COOKIE['INVITED_STATUS'],
                                'currency' => 0,
                                'ip' => $IP,
                                'image' => $data['data']['figureurl_2'],
                                'name' => $data['data']['nickname'],
                                'state' => 1,
                                'recent_time' => $date,
                                'found_date' => $date
                            ]);
                        } else {
                            setcookie("INVITED_STATUS", null, time() - 3600 * 12 * 15, '/');
                            $b = $DB->insert('user', [
                                'grade' => $conf['userdefaultgrade'],
                                'user_idu' => $data['user_idu'],
                                'superior' => $Uty,
                                'currency' => 0,
                                'ip' => $IP,
                                'image' => $data['data']['figureurl_2'],
                                'name' => $data['data']['nickname'],
                                'state' => 1,
                                'recent_time' => $date,
                                'found_date' => $date
                            ]);
                        }
                    }
                }


                if ($b) { #登陆成功
                    $GETID = $DB->get('user', '*', [
                        'user_idu' => $data['user_idu'],
                        'state' => 1
                    ]);
                    if ($GETTE == 1) {
                        /**
                         * 写入邀请奖励！
                         */
                        $FTR = $DB->get('invite', '*', [
                            'ip' => $IP
                        ]);
                        if (!$FTR) { #如果IP已经存在,则无法奖励
                            $award = $conf['award']; #奖励点
                            userlog('邀请奖励', '恭喜您成功邀请到用户[' . $data['data']['nickname'] . ']特奖励您' . $award . $conf['currency'] . '！,再接再厉哦', $_COOKIE['INVITED_STATUS'], $award);
                            $DB->insert('invite', [
                                'uid' => $_COOKIE['INVITED_STATUS'],
                                'invitee' => $GETID['id'],
                                'award' => $award,
                                'ip' => $IP,
                                'creation_time' => $date
                            ]);
                            Hook::execute('UserInvite', [
                                'id' => $_COOKIE['INVITED_STATUS'],
                                'yid' => $GETID['id'],
                                'num' => $award
                            ]);
                        } else {
                            userlog('失败邀请', '系统判断您的邀请对象：[' . $data['data']['nickname'] . ']已经在其他账号接收过邀请,无法奖励！,请邀请真实用户！', $_COOKIE['INVITED_STATUS'], 0);
                        }
                    }

                    if ($GETID) query::OrderUser($GETID['id']);
                    include_once(SYSTEM_ROOT . "extend/GoodsCart.php");
                    if ($GETID) \extend\GoodsCart::UserCookieDer($GETID['id']);

                    setcookie("THEKEY", $data['user_idu'], time() + 3600 * 12 * 15, '/'); #存储15 登陆信息判断
                    $url = is_https(false) . href() . '/user/'; #登陆

                    Hook::execute('UserLogin', [
                        'name' => $GETID['name'],
                        'id' => $GETID['id']
                    ]);

                    header("Location:$url");
                    return false;
                } else { #登陆失败
                    show_msg('温馨提示', '登陆失败,请重新登陆=>' . $DB->error(), '4', './login.php');
                }
            }
        }
    }
}

/**
 * Class community
 * 社区对接
 */
class community
{

    public function getSign($param, $key)
    {
        $signPars = "";
        ksort($param);
        foreach ($param as $k => $v) {
            if ("sign" != $k && "" != $v) {
                $signPars .= $k . "=" . $v . "&";
            }
        }
        $signPars = trim($signPars, '&');
        $signPars .= $key;
        $sign = md5($signPars);
        return $sign;
    }

    public static function __Data_acquisition_of_jiuwu($type, $_QET, $dats = null, $types = null)
    {
        $DB = \Medoo\DB\SQL::DB();
        $A = $DB->get('shequ', '*', [
            'id' => $_QET['id'],
        ]);
        if (!strstr($A['url'], 'http://') && !strstr($A['url'], 'https://')) { #未包含http://修正
            $A['url'] = 'http://' . $A['url'] . '/';
        }
        switch ($type) {
            case 1: #查询商品列表
                $_data = get_curl($A['url'] . '/index.php?m=home&c=api&a=get_goods_lists'); #查询商品列表
                return $_data;
                break;
            case 2: #查询详细+价格
                $a = get_curl($A['url'] . '/index.php?m=home&c=api&a=user_get_goods_lists_details&Api_UserName=' . $A['username'] . '&Api_UserMd5Pass=' . md5($A['password'])); #查询商品列表

                $data_post = [
                    'username' => $A['username'],
                    'password' => $A['password'],
                    'url' => $A['url'],
                    'gid' => $_QET['gid'],
                    'tyid' => $_QET['typs'],
                    'encrypt' => 0,
                ];
                if ($A['pattern'] == 1) {
                    include_once ROOT . 'includes/extend/Share.php';
                    include_once ROOT . 'includes/extend/jiuwu.php';
                    $b = jiuwu::TakeOutTheData($data_post);
                } else {
                    $data = json_encode($data_post);
                    $data = base64_encode($data);
                    $b = Curl::curl(false, ['data' => $data], true, '/jiuwuapi/api', 0);
                    $b = json_decode(base64_decode($b, true), true);
                }
                $data = json_decode($a, true);
                $data = [
                    'data_1' => $data,
                    'data_2' => $b
                ];
                return $data;
                break;
        }
    }

    public function jiuwu_regular($data)
    {
        $regex4 = "/<p class=\"error\".*?>.*?<\/p>/";
        if (preg_match_all($regex4, $data, $matches)) {
            $info = str_replace('<p class="error">', null, $matches[0][0]);
            $info = str_replace('</p>', null, $info);
            return [
                'info' => $info
            ];
        } else {
            return '无法获取的返回信息！';
        }
    }

    public function __Eilek_data_acquisition($type, $_QET, $datas = null, $types = null)
    {
        $DB = \Medoo\DB\SQL::DB();
        $A = $DB->get('shequ', '*', [
            'id' => $_QET['id'],
        ]);
        $api_token = $A['username'];
        $key = $A['password'];
        $params = [
            'api_token' => $api_token,
            'timestamp' => time(),
            'gid' => $_QET['gid']
        ];

        if (!strstr($A['url'], 'http://') && !strstr($A['url'], 'https://')) { #未包含http://修正
            $A['url'] = 'http://' . $A['url'] . '/';
        }

        /** 公共参数类end  */
        switch ($type) {
            case 1: #算法
                $sign = community::getSign($params, $key);
                return $sign;
                break;
            case 2: #获取商品列表
                $arr_datr = [
                    'api_token' => $api_token,
                    'timestamp' => time(),
                    'sign' => community::__Eilek_data_acquisition(1, $_QET)
                ];
                $A['url'] = str_replace("http://", "", $A['url']);
                $A['url'] = str_replace("https://", "", $A['url']);
                $A['url'] = str_replace("/", "", $A['url']);

                $data = get_curl($A['url'] . '.api.94sq.cn/api/goods/list', $arr_datr);
                return $data;
                break;
            case 3: #获取指定商品信息
                $_QET['gid'] = (int)$_QET['gid'];
                $arr_datr = [
                    'api_token' => $api_token,
                    'timestamp' => time(),
                    'sign' => community::__Eilek_data_acquisition(1, $_QET),
                    'gid' => $_QET['gid']
                ];
                $A['url'] = str_replace("http://", "", $A['url']);
                $A['url'] = str_replace("https://", "", $A['url']);
                $A['url'] = str_replace("/", "", $A['url']);

                $data = get_curl($A['url'] . '.api.94sq.cn/api/goods/info', $arr_datr);
                return $data;
                break;
        }
    }

    public static function __With_the_system($_QET)
    {
        $DB = \Medoo\DB\SQL::DB();
        $A = $DB->get('shequ', '*', ['id' => $_QET['sqid']]);
        if (!strstr($A['url'], 'http://') && !strstr($A['url'], 'https://')) { #未包含http://修正
            $A['url'] = 'http://' . $A['url'] . '/';
        }
        $postdata = [
            'act' => 'Docking_goods',
            'sign' => Docking::sign(['url' => href(), 'id' => $A['username'], 'gid' => $_QET['goods_id']], $A['password']),
            'url' => href(),
            'id' => $A['username'],
            'gid' => $_QET['goods_id'],
        ];
        $Data = get_curl($A['url'] . '/api.php', $postdata);
        return $Data;
    }

    /**
     * @param $type 类型
     * @param $_QET 参数1
     * @param null $input 下单信息
     * @param null $dats 参数2
     * @param null $types 返回类型
     * 卡易信操作类
     */
    public static function __Kamun_system($type, $_QET, $input = null, $dats = null, $types = null)
    {
        global $accredit;
        $DB = \Medoo\DB\SQL::DB();
        $A = $DB->get('shequ', '*', [
            'id' => $_QET['id'],
        ]);
        if (!strstr($A['url'], 'http://') && !strstr($A['url'], 'https://')) { #未包含http://修正
            $A['url'] = 'http://' . $A['url'] . '/';
        }
        switch ($type) {
            case 1: #获取卡易信商品目录
                $post = [
                    'username' => $A['username'],
                    'password' => $A['password'],
                    'url' => $A['url'],
                    'domain' => href(),
                    'cache' => (int)($_QET['cache'] == '' ? '1' : $_QET['cache']),
                ];
                if ($A['pattern'] == 1) {
                    include_once ROOT . 'includes/extend/Share.php';
                    include_once ROOT . 'includes/extend/kamun.php';
                    $data = json_encode(kamun::Catalogue($post));
                } else {
                    $data = Curl::curl(false, $post, true, '/Kamun/catalogue_api', 1);
                }
                break;
            case 2: #获取卡易信商品目录下的商品列表
                $post = [
                    'username' => $A['username'],
                    'password' => $A['password'],
                    'url' => $A['url'],
                    'domain' => href(),
                    'cache' => (int)($_QET['cache'] == '' ? '1' : $_QET['cache']),
                    'dirId' => xiaochu_en($_QET['dirId']),
                    'page' => ($_QET['page'] == '' ? 1 : $_QET['page']),
                ];
                if ($A['pattern'] == 1) {
                    include_once ROOT . 'includes/extend/Share.php';
                    include_once ROOT . 'includes/extend/kamun.php';
                    $data = json_encode(kamun::GoodsList($post));
                } else {
                    $data = Curl::curl(false, $post, true, '/Kamun/shop_list_api', 1);
                }
                break;
            case 3: #获卡易信详细商品信息
                $post = [
                    'username' => $A['username'],
                    'password' => $A['password'],
                    'url' => $A['url'],
                    'token' => $accredit['token'],
                    'domain' => href(),
                    'cache' => (int)($_QET['cache'] == '' ? '1' : $_QET['cache']),
                    'url_shop' => xiaochu_en(htmlspecialchars_decode($_QET['gid']))
                ];
                if ($A['pattern'] == 1) {
                    include_once ROOT . 'includes/extend/Share.php';
                    include_once ROOT . 'includes/extend/kamun.php';
                    $data = json_encode(kamun::GoodsDetails($post));
                } else {
                    $data = Curl::curl(false, $post, true, '/Kamun/shop_api', 1);
                }
                break;
            case 5: #获取对接卡易信余额
                $post = [
                    'username' => $A['username'],
                    'password' => $A['password'],
                    'url' => $A['url'],
                    'token' => $accredit['token'],
                    'domain' => href(),
                    'cache' => 1, //默认开启缓存
                ];
                if ($A['pattern'] == 1) {
                    include_once ROOT . 'includes/extend/Share.php';
                    include_once ROOT . 'includes/extend/kamun.php';
                    $data = json_encode(kamun::Money($post));
                } else {
                    $data = Curl::curl(false, $post, true, '/Kamun/money_api', 1);
                }
                break;
        }
        return $data;
    }
}

/**
 * @param string $ip
 * @return bool|mixed|string
 * 获取用户IP详细地址！
 */
function getCity($ip = '')
{
    $url = 'http://whois.pconline.com.cn/ipJson.jsp?json=true&ip=';
    $city = get_curl($url . $ip);
    $city = mb_convert_encoding($city, "UTF-8", "GB2312");
    $city = json_decode($city, true);
    if ($city['city']) {
        $location = $city['pro'] . $city['city'];
    } else {
        $location = $city['pro'];
    }
    if ($location) {
        return $location;
    } else {
        return false;
    }
}

/**
 * @return bool|string
 * 获取服务器IP地址
 */
function getServerIp()
{
    $url = 'http://members.3322.org/dyndns/getip';
    $url2 = 'https://www.bt.cn/Api/getIpAddress';
    if ($data = get_curl($url2)) {
        return $data;
    } else {
        $data = get_curl($url);
        if ($data == '') {
            return gethostbyname(href());
        }
        return $data;
    }
}

/**
 * @return mixed 获取当前来访域名ip 和用户ip
 */
function userip($type = 0)
{
    $ip = $_SERVER['REMOTE_ADDR'];
    if ($type <= 0 && isset($_SERVER['HTTP_X_FORWARDED_FOR']) && preg_match_all('#\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}#s', $_SERVER['HTTP_X_FORWARDED_FOR'], $matches)) {
        foreach ($matches[0] as $xip) {
            if (filter_var($xip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
                $ip = $xip;
                break;
            }
        }
    } elseif ($type <= 0 && isset($_SERVER['HTTP_CLIENT_IP']) && filter_var($_SERVER['HTTP_CLIENT_IP'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif ($type <= 1 && isset($_SERVER['HTTP_CF_CONNECTING_IP']) && filter_var($_SERVER['HTTP_CF_CONNECTING_IP'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
        $ip = $_SERVER['HTTP_CF_CONNECTING_IP'];
    } elseif ($type <= 1 && isset($_SERVER['HTTP_X_REAL_IP']) && filter_var($_SERVER['HTTP_X_REAL_IP'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
        $ip = $_SERVER['HTTP_X_REAL_IP'];
    }
    return $ip;
}

/**
 * @param $act 字段名称
 * @param $cs  判断参数
 * @param $Data 数据
 * 数据存储,只可存储json数据
 */
function HomecachingAdd($act = '', $cs = [], $Data = [])
{
    $Flie = ROOT . '/includes/extend/log/Home/Cache_' . md5($act . json_encode($cs)) . '.cache';
    @file_put_contents($Flie, json_encode($Data, JSON_UNESCAPED_UNICODE));
    return true;
}

/**
 * @param $act 字段名称
 * @param $cs  判断参数
 * 数据验证
 */
function HomecachingVerify($act, $cs = [])
{
    global $conf;
    $Flie = ROOT . '/includes/extend/log/Home/Cache_' . md5($act . json_encode($cs)) . '.cache';
    if (file_exists($Flie)) {
        $tiem = (float)filemtime($Flie);
        if ((time() - $tiem) < $conf['Homecaching']) {
            return json_decode(file_get_contents($Flie), TRUE);
        }
        return false;
    } else return false;
}

/**
 * 删除
 */
function HomecachingUnlink($act, $cs = [])
{
    $Flie = ROOT . '/includes/extend/log/Home/Cache_' . md5($act . json_encode($cs)) . '.cache';
    if (unlink($Flie)) return true;
    return false;
}

/**
 * @param $str 本地图片地址
 * URL本地连接转换为外链
 * /assets/img/ path
 */
function ImageUrl($str, $Url = false)
{
    if ($Url == false) {
        $Url = is_https(false) . href();
    }
    if ($str == '') return '';
    $arr = explode('/', $str);
    if ($arr[0] == '' && $arr[1] == 'assets' && $arr[2] == 'img') {
        return $Url . $str;
    } else if ($arr[0] == 'assets' && $arr[1] == 'img') {
        return $Url . '/' . $str;
    } else if ($arr[1] == 'includes' && $arr[2] == 'extend' && $arr[3] == 'log') {
        return $Url . $str;
    } else if ($arr[0] == '' && $arr[1] == 'assets') {
        return $Url . '/' . $str;
    } else {
        return $str;
    }
}

/**
 * @param $arr i=!isset || e=empty 验证
 * 验证是否填写完整！
 */
function test($arr, $msg = '')
{
    foreach ($arr as $value) {
        global $_QET;
        $r = explode('|', $value);
        if ($r[1] == 'i' && !isset($_QET[$r[0]])) {
            if ($msg == '') dies(-1, '请将参数：' . $r[0] . ' 填写完整！');
            dies(-1, $msg);
        }
        if ($r[1] == 'e' && empty($_QET[$r[0]])) {
            if ($msg == '') dies(-1, '请将参数：' . $r[0] . ' 填写完整！');
            dies(-1, $msg);
        }
    }
}


/**
 * @param $dir
 * @param int $mode
 * @return bool
 * 检测目录是否存在，不存在则创建
 */
function mkdirs($dir, $mode = 0777)
{
    if (is_dir($dir) || @mkdir($dir, $mode)) {
        return true;
    }
    if (!mkdirs(dirname($dir), $mode)) {
        return false;
    }
    return @mkdir($dir, $mode);
}

/**
 * 是否为https
 * @return bool
 */
function is_https($type = true, $ts = 1)
{
    if (!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off') {
        if ($type == true) {
            return true;
        } else {
            if ($ts == 2) {
                return 'https';
            } else  return 'https://';
        }
    } elseif (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') {
        if ($type == true) {
            return true;
        } else {
            if ($ts == 2) {
                return 'https';
            } else  return 'https://';
        }
    } elseif (!empty($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off') {
        if ($type == true) {
            return true;
        } else {
            if ($ts == 2) {
                return 'https';
            } else  return 'https://';
        }
    }
    if ($type == true) {
        return false;
    } else {
        if ($ts == 2) {
            return 'http';
        } else  return 'http://';
    }
}

/**
 * @param $str
 * @param $leftStr
 * @param $rightStr
 * @return false|string
 * 取中间值
 */
function getSubstr($str, $leftStr, $rightStr)
{
    if ($rightStr == '') {
        return explode($leftStr, $str)[1];
    } else {
        $left = strpos($str, $leftStr);
        $right = strpos($str, $rightStr, $left);
        if ($left < 0 or $right < $left) {
            return '';
        }
        return substr($str, $left + strlen($leftStr), $right - $left - strlen($leftStr));
    }
}


/**
 * @param $dir 待删除的文件夹名称
 * @return bool
 * 删除指定文件夹！
 */
function DelDir($dir)
{
    if (!is_dir($dir)) {
        return false;
    }
    $dh = opendir($dir);
    while ($file = readdir($dh)) {
        if ($file != "." && $file != "..") {
            $fullpath = $dir . "/" . $file;
            if (!is_dir($fullpath)) {
                unlink($fullpath);
            } else {
                DelDir($fullpath);
            }
        }
    }
    closedir($dh);
    if (rmdir($dir)) {
        return true;
    } else {
        return false;
    }
}


class background
{
    public function image()
    {
        global $conf;
        switch ($conf['background']) {
            case 1:
                return 'background-image: url(' . background::Bing_day() . ');-webkit-background-size: cover和-o-background-size: cover';
                break;
            case 2:
                return 'background-image: url(' . background::Bing_random() . ');-webkit-background-size: cover和-o-background-size: cover';
                break;
            case 3:
                return 'background-image: url(' . background::anime() . ');-webkit-background-size: cover和-o-background-size: cover';
                break;
            case 4:
                return false;
                break;
            case 5:
                return 'background:#ecedf0 url(/assets/img/bj.png) fixed;background-repeat:repeat;';
                break;
            default:
                return 'background-image: url(' . background::Bing_day() . ')';
                break;
        }
    }

    public function Bing_day()
    {
        return 'https://acg.xydwz.cn/api/api.php';
    }

    public function Bing_random()
    {
        return 'https://api.ixiaowai.cn/gqapi/gqapi.php';
    }

    public function anime()
    {
        return 'http://api.mtyqx.cn/api/random.php';
    }
}

/**
 * @param $url
 * @return bool
 * 验证远程文件地址是否有效
 */
function file_exists_image($url)
{
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_NOBODY, true);
    $result = curl_exec($curl);
    if ($result !== false) {
        return true;
    } else return false;
}

/**
 * @param int $Type 1=返回二维码图片地址，2=输出图片或生成图片
 * @param string $url //内容
 * @param int $w //宽高
 * @param int $m //间距
 * @param bool $outfile
 * @param bool $outfiles
 * 二维码生成方法
 */
function QR_Code($Type = 1, $url = '请将text参数填写完整，可传递域名，文字等信息！', $w = 6, $m = 1, $outfile = false, $outfiles = false)
{
    include(SYSTEM_ROOT . 'extend/phpqrcode.php');
    if ($Type == 1) {
        QRcode::png($url, $outfile, QR_ECLEVEL_H, $w, $m, false);
        return ($outfiles == false ? $outfile : $outfiles);
    } else return QRcode::png($url, $outfile, QR_ECLEVEL_H, $w, $m, false);
}
